package net.aiform.web.security;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.config.ParentPackage;
import org.apache.struts2.config.Result;
import org.apache.struts2.config.Results;
import org.apache.struts2.dispatcher.ServletActionRedirectResult;
import org.springframework.beans.factory.annotation.Required;
import org.springside.modules.utils.CollectionUtils;
import org.springside.modules.web.struts2.CRUDActionSupport;

import net.aiform.entity.security.Authority;
import net.aiform.entity.security.Sysrole;
import net.aiform.service.security.SecurityManager;

/**
 * 角色管理Action.
 * 
 * @see CRUDActionSupport
 * @author calvin
 */
@ParentPackage("default")
@Results({
@Result(name=CRUDActionSupport.RELOAD, value="role", type=ServletActionRedirectResult.class)
})
public class RoleAction extends CRUDActionSupport<Sysrole> {

	private static final long serialVersionUID = 8517636900960039101L;

	private SecurityManager manager;

	private List<Sysrole> allRoles;

	private Sysrole entity;

	private String id;

	private List<String> checkedAuthIds;

	private List<Authority> allAuths;

	public Sysrole getModel() {
		return entity;
	}

	public List<Sysrole> getAllRoles() {
		return allRoles;
	}

	public List<Authority> getAllAuths() {
		return allAuths;
	}

	public List<String> getCheckedAuthIds() {
		return checkedAuthIds;
	}

	public void setCheckedAuthIds(List<String> checkedAuthIds) {
		this.checkedAuthIds = checkedAuthIds;
	}

	public void setId(String id) {
		this.id = id;
	}

	@Override
	public String list() throws Exception {
		allRoles = manager.getAllRoles();
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		allAuths = manager.getAllAuths();
		checkedAuthIds = entity.getAuthIds();
		return INPUT;
	}

	@Override
	public String save() throws Exception {
		//根据页面上的checkbox 整合entity的auth Set.
		CollectionUtils.mergeByCheckedIds(entity.getAuthorities(), checkedAuthIds, Authority.class);
		manager.saveRole(entity);

		return RELOAD;
	}

	@Override
	public String delete() throws Exception {
		manager.deleteRole(id);
		return RELOAD;
	}

	@Required
	public void setSecurityManager(SecurityManager securityManager) {
		manager = securityManager;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (!StringUtils.isBlank(id)) {
			entity = manager.getRole(id);
		} else {
			entity = new Sysrole();
		}
	}
}